import { reqCode, reqUserRegister, reqUserLogin, reqGetUserInfo, reqLoginOut } from '@/api'
import { setToken, getToken, removeToken } from '@/utils/token'
//登录和注册模块
const state = {
    code: '',
    //令牌  通过token 向服务器发请求 得到用户信息
    token: getToken(),
    userInfo: {}
}
const mutations = {
    GETCODE(state, code) {
        state.code = code;
    },
    USERLOGIN(state, token) {
        state.token = token
    },
    USERINFO(state, userInfo) {
        state.userInfo = userInfo
    },
    //退出登录 清除用户信息
    CLEARUSERINFO(state) {
        state.code = '';
        state.userInfo = '';
        removeToken()
    }
}
const actions = {
    //获取验证码
    async getCode({ commit }, phone) {
        let result = await reqCode(phone);
        if (result.code == 200) {
            commit('GETCODE', result.data);
            return 'ok'
        } else {
            return Promise.reject(new Error('fail'))
        }
    },
    //注册
    async userRegister({ commit }, user) {
        let result = await reqUserRegister(user)
        if (result.code == 200) {
            return 'ok'
        } else {
            return Promise.reject(new Error('fail'))
        }
    },
    //登录
    async userLogin({ commit }, data) {
        let result = await reqUserLogin(data)
        // 服务器下发token，用户唯一标识（uuid）
        if (result.code == 200) {
            commit('USERLOGIN', result.data.token)
            //将用户信息存储到本地存储中，因为vuex 不持久化，一刷新token就没了
            setToken(result.data.token)
            return 'ok';
        } else {
            return Promise.reject(new Error('fail'))
        }
    },
    // 获取用户信息
    async userInfo({ commit }) {
        let result = await reqGetUserInfo();
        if (result.code == 200) {
            commit('USERINFO', result.data);
            return 'ok'
        } else {
            return Promise.reject(new Error('fail'))
        }
    },
    //退出登录
    async loginOut({ commit }) {
        let result = await reqLoginOut();
        if (result.code == 200) {
            commit('CLEARUSERINFO');
            return 'ok'
        } else {
            return Promise.reject(new Error('fail'))
        }
    }
}
const getters = {}
export default {
    state,
    mutations,
    actions,
    getters
}